package com.emily.test.controller;

import com.alibaba.fastjson.JSONObject;
import com.emily.test.constant.ReturnValueConstants;
import com.emily.test.controller.result.ResponseResult;
import com.emily.test.model.TResource;
import com.emily.test.service.RedisService;
import com.emily.test.service.TCompanyResourceService;
import com.emily.test.service.TResourceService;
import com.emily.test.utils.ConstentUtil;
import com.emily.test.utils.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping(value = "tResourceController")
@Api(value = "TResourceApi", description = "TResource接口类", position = 1, produces = MediaType.APPLICATION_JSON_VALUE)
public class TResourceController {

    private Logger logger = LoggerFactory.getLogger(TResourceController.class);

    @Autowired
    private TResourceService tResourceService;
    @Autowired
    private RedisService redisService;

    @Autowired
    private TCompanyResourceService tCompanyResourceService;
    /**
     * 文件服务器请求路径
     */
    @Value(value="${filePath}")
    private String FilePath;

    @ApiOperation(value = "获取资源信息", notes = "TResource")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "资源ID", required = true)
    })
    @PostMapping(value = "selectTResourceInfoById")
    public ResponseResult selectByPrimaryKey(@RequestBody JSONObject jsonObject) {
        int id = jsonObject.getInteger("id");

        try {
            TResource tResource = tResourceService.selectByPrimaryKey(id);
            logger.info("获取TResourceService={}", tResource);
            return ResponseResult.success(ReturnValueConstants.QUERY_SUCCESS, tResource);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取TResourceService异常:{}", e);
            return ResponseResult.fail(ReturnValueConstants.QUERY_FAILURE);
        }

    }

    @ApiOperation(value = "增加一条资源", notes = "TResource")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "resName", value = "资源名称", required = true),
            @ApiImplicitParam(name = "img", value = "图片"),
            /*@ApiImplicitParam(name = "pageurl", value = "资源URL"),*/
            @ApiImplicitParam(name = "state", value = "是否启用"),
            /* @ApiImplicitParam(name = "pid", value = "父节点ID"),*/
            @ApiImplicitParam(name = "description", value = "备注")
    })
    @PostMapping(value = "insertTResourceInfo")
    public ResponseResult insertTResourceInfo(@RequestBody JSONObject jsonObject) {
//        File file=(File) jsonObject.get("img");
        try {
            TResource tResource = (TResource) ConstentUtil.json2Object(jsonObject, TResource.class);
            System.out.println(tResource);
            tResource.setUpdateTime(DateUtil.getNowStr());
            int num = tResourceService.insertTResource(tResource);
            logger.info("添加资源信息成功,resource={}", tResource);
            return ResponseResult.success(ReturnValueConstants.ADD_SUCCESS, num);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("添加资源信息失败,异常:{}", e);
            return ResponseResult.fail(ReturnValueConstants.ADD_FAILURE);
        }
    }
//    @ApiOperation(value = "上传文件到服务器的img文件夹下", notes = "TResource")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "id", value = "资源ID", required = true)
//    })
//    @RequestMapping("fileUploadToServer")
//    public ResponseResult fileUploadToServer(File file1,HttpServletRequest request,HttpServletResponse response) throws IOException, FileUploadException {
//
//        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
//        if (!isMultipart){
//            throw new IllegalArgumentException(
//                    "上传内容不是有效的multipart/form-data类型.");
//        }
//        // Create a1 factory for disk-based file items
//        DiskFileItemFactory factory = new DiskFileItemFactory();
//
//        // Create a1 new file upload handler
//        ServletFileUpload upload = new ServletFileUpload(factory);
//
//        // 设置上传内容的大小限制（单位：字节）
//        upload.setSizeMax(ReturnValueConstants.YOUR_MAX_REQUEST_SIZE);
//        // Parse the request
//        List<?> items = upload.parseRequest(request);
//        String filePath="";
//        Iterator iter = items.iterator();
//        String rename="";
//
//        while (iter.hasNext()) {
//            FileItem item = (FileItem) iter.next();
//
//            if (item.isFormField()) {
//                // 如果是普通表单字段
////                String name = item.getFieldName();
////                String value = item.getString();
//                // ...
//            }else {
//                // 如果是文件字段
//                String fieldName = item.getFieldName();
//                String fileName = item.getName();
//                fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
//                String houzhui = fileName.substring(fileName.lastIndexOf("."));
//                String contentType = item.getContentType();
//                boolean isInMemory = item.isInMemory();
//                long sizeInBytes = item.getSize();
//
//                rename = UUID.randomUUID()+houzhui;
////                fileItem.write(new File(path, rename));
//
//                // ...
//
//                //上传到远程服务器
//                InputStream uploadedStream = item.getInputStream();
//                Map<String,Object> files=new HashMap<String,Object>();
//
//                files.put("fileName",rename);
////                files.put("fileContentType",contentType);
//
//                HashMap<String, InputStream> file = new HashMap<String, InputStream>();
//                file.put(fileName,uploadedStream);
//
//                files.put("inputStream", file);
//                filePath= FileOperateUtil.fileUpload(files,request);
//                uploadedStream.close();
//            }
//        }
//        return ResponseResult.success(filePath);
//    }

    @ApiOperation(value = "修改一条资源的其中某些信息", notes = "TResource")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "资源ID", required = true),
            @ApiImplicitParam(name = "resName", value = "资源名称"),
            @ApiImplicitParam(name = "img", value = "图片"),
            /*@ApiImplicitParam(name = "pageurl", value = "资源URL"),*/
            @ApiImplicitParam(name = "state", value = "是否启用"),
            /* @ApiImplicitParam(name = "pid", value = "父节点ID"),*/
            @ApiImplicitParam(name = "description", value = "备注")
    })
    @PostMapping(value = "updateSomeTResourceInfo")
    public ResponseResult updateSomeTResourceInfo(@RequestBody JSONObject jsonObject) {
        try {
            TResource tResource = (TResource) ConstentUtil.json2Object(jsonObject, TResource.class);
            tResource.setUpdateTime(DateUtil.getNowStr());
            int num = tResourceService.updateSomeTResourceInfo(tResource);
            logger.info("修改资源的信息成功,resource={}", tResource);
            return ResponseResult.success(ReturnValueConstants.UPDATE_SUCCESS, num);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("修改资源的信息异常:{}", e);
            return ResponseResult.fail(ReturnValueConstants.UPDATE_FAILURE);
        }
    }

    @ApiOperation(value = "修改一条资源的全部信息", notes = "TResource")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "资源ID", required = true),
            @ApiImplicitParam(name = "resName", value = "资源名称"),
            @ApiImplicitParam(name = "img", value = "图片"),
            /*@ApiImplicitParam(name = "pageurl", value = "资源URL"),*/
            @ApiImplicitParam(name = "state", value = "是否启用", required = true),
            /*@ApiImplicitParam(name = "updateTime", value = "修改时间",required = true),*/
            /* @ApiImplicitParam(name = "pid", value = "父节点ID"),*/
            @ApiImplicitParam(name = "description", value = "备注")
    })
    @PostMapping(value = "updateAllTResourceInfo")
    public ResponseResult updateAllTResourceInfo(@RequestBody JSONObject jsonObject) {
        try {
            TResource tResource = (TResource) ConstentUtil.json2Object(jsonObject, TResource.class);
            tResource.setUpdateTime(DateUtil.getNowStr());
            int num = tResourceService.updateAllTResourceInfo(tResource);
            logger.info("修改资源信息成功,resource={}", tResource);
            return ResponseResult.success(ReturnValueConstants.UPDATE_SUCCESS, num);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("修改资源信息异常：", e);
            return ResponseResult.fail(ReturnValueConstants.UPDATE_FAILURE);
        }
    }

    @ApiOperation(value = "根据ID删除资源信息", notes = "TResource")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "资源ID", required = true)
    })
    @PostMapping(value = "deleteTResourceById")
    public ResponseResult deleteTResourceById(@RequestBody JSONObject jsonObject) {
        try {

            int id = jsonObject.getInteger("id");
            TResource tResource = new TResource();
            tResource.setId(id);
            tResource.setState(2);
            tResource.setUpdateTime(DateUtil.getNowStr());
            int num = tResourceService.updateByPrimaryKeySelective(tResource);
            logger.info("删除资源信息成功,resourceId={}", id);
            return ResponseResult.success(ReturnValueConstants.DELATE_SUCCESS, num);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("删除资源信息异常:{}", e);
            return ResponseResult.fail(ReturnValueConstants.DELATE_FAILURE);
        }
    }


    @ApiOperation(value = "查询资源信息列表", notes = "TResource")
   /* @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "资源ID", required = true)
    })*/
    @PostMapping(value = "selectResourceList")
    public ResponseResult selectResourceList() {
        try {
            List<TResource> resourceList = tResourceService.getResourceList();
            logger.info("查询资源信息列表成功,resourceList={}", resourceList);
            return ResponseResult.success(ReturnValueConstants.QUERY_SUCCESS, resourceList);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询资源信息列表异常:{}", e);
            return ResponseResult.fail(ReturnValueConstants.QUERY_FAILURE);
        }
    }

    /**
     * 根据角色ID查询对应的资源信息列表
     *
     * @param jsonObject 角色id集合，其中参数key为roleIds，值形式为:"1,2,3,4"
     * @return
     */
    @ApiOperation(value = "根据角色ID集合查询所有相关资源ID", notes = "TRoleResource")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleIds", value = "角色ID集合", required = true)
    })
    @PostMapping(value = "selectTReSourceInfoByRoleIds")
    public ResponseResult selectTReSourceInfoByRoleIds(@RequestBody JSONObject jsonObject) {
        String roleIds = jsonObject.getString("roleIds");
        try {
            List<Map<String,Object>> tResourceList= tResourceService.selectTReSourceInfoListByRoleIds(ConstentUtil.strToList(roleIds));
            String[] strs = roleIds.split(",");
            List alllist = new ArrayList();
            for (int j = 0; j < strs.length; j++) {
                HashMap<String, Object> hm = new HashMap<>();
                List list1 = new ArrayList();
                for (int i = 0; i < tResourceList.size(); i++) {
                    if(strs[j].equals(tResourceList.get(i).get("roleId").toString())) {
                        hm.put("roleId", strs[j]);
                        hm.put("rName", tResourceList.get(i).get("rName").toString());
                        list1.add(tResourceList.get(i));
                        hm.put("data",list1);
                    }
                }
                if(hm.size()!=0){
                    alllist.add(hm);
                }
            }
            logger.info("查询t_resource成功，list={}",alllist);
            return ResponseResult.success(ReturnValueConstants.QUERY_SUCCESS,alllist);
        } catch (Exception e) {
            logger.error("查询t__resource异常:{}", e);
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.QUERY_FAILURE);
        }
    }
    @ApiOperation(value = "根据公司id获取首页信息列表", notes = "")
    @PostMapping(value = "selectIndexList")
    public ResponseResult selectIndexList(HttpServletRequest request, HttpServletResponse response) {
        try {
            String token = request.getHeader("token");
            System.out.println("token===="+token);
            Map<String,Object> userMap=  (Map<String,Object>)redisService.get(token);
            Integer id = (Integer) userMap.get("companyId");
            if(ConstentUtil.isEmpty(id)){
                return ResponseResult.fail("请联系管理员将您添加到公司!");
            }
            List<Map<String,Object>> resourceList=new ArrayList<Map<String,Object>>();
//            if("SHANDONGHAIHUI".equals(companyCode)){
//                List<TResource> resList=tResourceService.getResourceList();
//                logger.info(ReturnValueConstants.QUERY_SUCCESS+",用户信息:{}",userMap);
//                return ResponseResult.success( resList);
//            }
            resourceList= tCompanyResourceService.selectTCompanyResourceInfoByCompanyId(id);
            return ResponseResult.success(ReturnValueConstants.QUERY_SUCCESS, resourceList);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询资源信息列表异常:{}", e);
            return ResponseResult.fail(ReturnValueConstants.QUERY_FAILURE);
        }
    }

    /**
     * 根据资源id查询出资源的子节点信息集合
     * @param jsonObject 资源id，其中包括{"id": 1}
     * @return
     */
    @ApiOperation(value = "根据资源id获取其子节点的启用资源列表", notes = "TResource")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "资源ID", required = true)
    })
    @PostMapping(value = "selectChildResourceListById")
    public ResponseResult selectChildResourceListById(@RequestBody JSONObject jsonObject) {
        Integer id=jsonObject.getInteger("id");
        TResource tResource=new TResource();
        tResource.setPid(id);
        tResource.setState(1);
        try {
            List<TResource> resourceList= tResourceService.selectResourceListByCondition(tResource);
            return ResponseResult.success(resourceList);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询资源信息列表异常:{}", e);
            return ResponseResult.fail(ReturnValueConstants.QUERY_FAILURE);
        }
    }
    @ApiOperation(value = "上传图片接口")
    @PostMapping(value = "/upload")
    public ResponseResult upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseResult.fail("1", "失败");
        }
        JSONObject postData = new JSONObject();
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID() + suffixName;
        try {
            byte[]  fileBytes = file.getBytes();
            postData.put("fileName",fileName);
            postData.put("data",fileBytes);
            RestTemplate client = new RestTemplate();
            JSONObject json = client.postForEntity(FilePath, postData, JSONObject.class).getBody();
            System.out.println(json);
            logger.info("上传成功");
            return ResponseResult.success("0", json.get("data"));
        } catch (IOException e) {
            logger.error(e.toString(), e);
        }
        logger.info("上传失败");
        return ResponseResult.success("1","上传失败");
    }
    /**
     * 根据条件查询符合条件的资源信息
     * @param jsonObject 查询的条件
     * @return
     */
    @ApiOperation(value = "根据条件查询符合条件的资源信息", notes = "")
    @PostMapping(value = "selectResourceListByCondition")
    public ResponseResult selectResourceListByCondition(@RequestBody(required = false) JSONObject jsonObject) {
        TResource tResource=new TResource();
        if(!ConstentUtil.isEmpty(jsonObject)){
            Integer id=jsonObject.getInteger("id");
            String resName=jsonObject.getString("resName");
            String description=jsonObject.getString("description");
            Integer state=jsonObject.getInteger("state");
            String pageurl=jsonObject.getString("pageurl");
            String updateTime=jsonObject.getString("updateTime");
            String img=jsonObject.getString("img");
            Integer pid=jsonObject.getInteger("pid");
            tResource.setId(id);
            tResource.setResName(resName);
            tResource.setUpdateTime(updateTime);
            tResource.setState(state);
            tResource.setDescription(description);
            tResource.setImg(img);
            tResource.setPageurl(pageurl);
            tResource.setPid(pid);
        }
        try {
            List<TResource> resourceList= tResourceService.selectResourceListByCondition(tResource);
            return ResponseResult.success(resourceList);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询资源信息列表异常:{}", e);
            return ResponseResult.fail(ReturnValueConstants.QUERY_FAILURE);
        }
    }
    /**
     * 禁用多个资源
     * @param jsonObject    其中资源ids的格式为:ids={1,2,3,4}
     * @return
     */
    @ApiOperation(value="禁用多个资源", notes="根据id禁用资源信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "资源ID列表", required = true)
    })
    @PostMapping(value = "disabledResourceById")
    public ResponseResult disabledResourceById(@RequestBody JSONObject jsonObject){
        String ids=jsonObject.getString("ids").replaceAll("\\[","").replaceAll("]","");
        String[] idStr=ids.split(",");
        List<TResource> tResourceList=new ArrayList<TResource>();
        if(idStr.length !=0){
            for( int i=0;i<idStr.length;i++){
                TResource tResource=new TResource();
                tResource.setId(ConstentUtil.strToInteger(idStr[i]));
                tResource.setState(0);
                tResourceList.add(tResource);
                tCompanyResourceService.delByReId(ConstentUtil.strToInteger(idStr[i]));
            }
        }
        try {
            int num=tResourceService.updateResourceInfoByIds(tResourceList);
            logger.info("ids为{}的资源已禁用",ids);
            return ResponseResult.success("0","禁用成功",tResourceList);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail("禁用失败");
        }
    }

    /**
     * 启用多个资源
     * @param jsonObject    其中资源ids的格式为:ids={1,2,3,4}
     * @return
     */
    @ApiOperation(value="启用多个资源信息", notes="根据id资源公司信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "资源ID列表", required = true)
    })
    @PostMapping(value = "enabledResourceById")
    public ResponseResult enabledResourceById(@RequestBody JSONObject jsonObject){
        String ids=jsonObject.getString("ids").replaceAll("\\[","").replaceAll("]","");
        String[] idStr=ids.split(",");
        List<TResource> tResourceList=new ArrayList<TResource>();
        if(idStr.length !=0){
            for( int i=0;i<idStr.length;i++){
                TResource tResource=new TResource();
                tResource.setId(ConstentUtil.strToInteger(idStr[i]));
                tResource.setState(1);
                tResourceList.add(tResource);
            }
        }
        try {
            int num=tResourceService.updateResourceInfoByIds(tResourceList);
            logger.info("ids为{}的资源已启用",ids);
            return ResponseResult.success("0","启用成功",tResourceList);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail("启用成功");
        }



    }
    /**
     * 删除资源（假删除，令state=2）
     * @param jsonObject    其中资源ids的格式为:{1,2,3,4}
     * @return
     */
    @ApiOperation(value="删除多个资源信息", notes="根据id删除资源信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "资源ID列表", required = true)
    })
    @PostMapping(value = "deleteResourceById")
    public ResponseResult deleteResourceById(@RequestBody JSONObject jsonObject){
        String ids=jsonObject.getString("ids").replaceAll("\\[","").replaceAll("]","");
        String[] idStr=ids.split(",");
        List<TResource> tResourceList=new ArrayList<TResource>();
        if(idStr.length !=0){
            for( int i=0;i<idStr.length;i++){
                TResource tResource=new TResource();
                tResource.setId(ConstentUtil.strToInteger(idStr[i]));
                tResource.setState(2);
                tResourceList.add(tResource);
                tCompanyResourceService.delByReId(ConstentUtil.strToInteger(idStr[i]));
            }

        }

        try {
            int num=tResourceService.updateResourceInfoByIds(tResourceList);
            logger.info("ids为{}的资源已删除",ids);
            return ResponseResult.success("0","删除成功",tResourceList);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail("删除失败");
        }
    }

}
